package org.neptune.service.websocket;

import java.util.Map;

import org.neptune.api.entity.Message;
import org.neptune.api.entity.WebSocketInfo;
import org.neptune.common.constant.NeptuneConstant;
import org.neptune.common.util.RandomUtils;
import org.neptune.service.util.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;

/**
 * @author lwl
 * @date 2020/10/24 15:42
 */
public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

	private Logger logger = LoggerFactory.getLogger(MyWebSocketHandler.class);

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.info("与客户端建立连接，通道开启！");
		AttributeKey<WebSocketInfo> attributeKey = AttributeKey.valueOf(NeptuneConstant.WEBSOCKET_USER);
		WebSocketInfo webSocketInfo = new WebSocketInfo(RandomUtils.createRandomUUID(),
				WebUtil.getLoginUser().getNickName());
		ctx.channel().attr(attributeKey).set(webSocketInfo);
		// 添加到channelGroup通道组
		MyChannelHandlerPool.channelGroup.add(ctx.channel());
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		logger.info("与客户端断开连接，通道关闭！");
		// 添加到channelGroup 通道组
		MyChannelHandlerPool.channelGroup.remove(ctx.channel());
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// 首次连接是FullHttpRequest，处理参数

		if (null != msg && msg instanceof FullHttpRequest){
			FullHttpRequest request = (FullHttpRequest) msg;
			String uri = request.uri();

			Map paramMap = getUrlParams(uri);
			logger.info("接收到的参数是：" + JSON.toJSONString(paramMap));
			// 如果url包含参数，需要处理
			if (uri.contains("?")){
				String newUri = uri.substring(0, uri.indexOf("?"));
				logger.info("old url :" + uri);
				logger.info("new url :" + newUri);
				request.setUri(newUri);
			}

		} else if (msg instanceof TextWebSocketFrame){
			// 正常的TEXT消息类型
			TextWebSocketFrame frame = (TextWebSocketFrame) msg;
			logger.info("客户端收到服务器数据：" + frame.text());
			Message message = JSON.parseObject(frame.text(), Message.class);
			// CommentProducer commentProducer = SpringApplicationContext
			// .getBeanByClass(CommentProducer.class);
			// commentProducer.sender(session, message.getMsg());
			AttributeKey<WebSocketInfo> attributeKey = AttributeKey.valueOf(NeptuneConstant.WEBSOCKET_USER);
			sendAllMessage(frame.text(), ctx.channel().attr(attributeKey).get().getUserName());
		}
		super.channelRead(ctx, msg);
	}

	@Override
	protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame)
			throws Exception {

	}

	private void sendAllMessage(String text, String user) {
		// 收到信息后，群发给所有channel
		String message = Message.jsonStr(Message.SPEAK, user, text, MyChannelHandlerPool.channelGroup.size());
		MyChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(message));
	}

	private static Map getUrlParams(String url) {
		Map<String, String> map = Maps.newHashMap();
		url = url.replace("?", ";");
		if (!url.contains(";")){
			return map;
		}
		if (url.split(";").length > 0){
			String[] arr = url.split(";")[1].split("&");
			for (String s : arr){
				String key = s.split("=")[0];
				String value = s.split("=")[1];
				map.put(key, value);
			}
			return map;
		} else{
			return map;
		}
	}
}
